<template>
	<div class="order-list-page">
		<!-- 顶部导航 -->
		<header class="page-header">
			<button class="back-btn" @click="goBack">
				<i class="material-icons">arrow_back</i>
			</button>
			<h1 class="page-title">我的订单</h1>
		</header>

		<!-- 主要内容 -->
		<main class="main-content">
			<!-- 加载状态 -->
			<div v-if="loading" class="loading-state">
				<div class="loading-spinner"></div>
				<p>加载订单中...</p>
			</div>
			
			<!-- 空状态 -->
			<div v-else-if="orderArr && orderArr.length === 0" class="empty-state">
				<i class="material-icons">shopping_cart</i>
				<p>暂无订单</p>
				<button class="mdc-button mdc-button--raised" @click="goToBusinessList">
					去下单
				</button>
			</div>
			
			<!-- 订单列表 -->
			<div v-else class="orders-container">
				<!-- 未支付订单 -->
				<section v-if="unpaidOrders && unpaidOrders.length > 0" class="order-section">
					<div class="section-header">
						<i class="material-icons">pending</i>
						<h3>待支付</h3>
						<span class="badge">{{ unpaidOrders ? unpaidOrders.length : 0 }}</span>
					</div>
					
					<div class="order-list">
						<div v-for="order in unpaidOrders" :key="order.orderId" class="order-card" @click="goToOrderDetail(order.orderId)">
							<div class="order-header" @click.stop="toggleOrderDetail(order)">
								<div class="business-info">
									<i class="material-icons">store</i>
									<span class="business-name">{{ order.businessName }}</span>
								</div>
								<div class="order-info">
									<span class="price">¥{{ order.totalPrice }}</span>
									<i class="material-icons" :class="{ 'rotated': order.isShowDetailet }">
										expand_more
									</i>
								</div>
							</div>
							
							<div v-show="order.isShowDetailet" class="order-details">
								<div class="detail-item" v-for="item in order.priceDetails" :key="item.foodName">
									<span class="item-name">{{ item.foodName }}</span>
									<span class="item-info">×{{ item.quantity }}</span>
									<span class="item-price">¥{{ (item.foodPrice * item.quantity).toFixed(2) }}</span>
								</div>
								<div class="detail-item delivery">
									<span class="item-name">配送费</span>
									<span class="item-price">¥{{ order.deliveryPrice }}</span>
								</div>
								<div class="detail-item total">
									<span class="item-name">总计</span>
									<span class="item-price total-price">¥{{ order.totalPrice }}</span>
								</div>
							</div>
							
							<div class="order-actions">
								<button class="mdc-button mdc-button--outlined" @click="cancelOrder(order.orderId)">
									取消订单
								</button>
								<button class="mdc-button mdc-button--raised pay-btn" @click="goToPayment(order.orderId)">
									去支付
								</button>
							</div>
						</div>
					</div>
				</section>

				<!-- 已支付订单 -->
				<section v-if="paidOrders && paidOrders.length > 0" class="order-section">
					<div class="section-header">
						<i class="material-icons">check_circle</i>
						<h3>已完成</h3>
						<span class="badge">{{ paidOrders ? paidOrders.length : 0 }}</span>
					</div>
					
					<div class="order-list">
						<div v-for="order in paidOrders" :key="order.orderId" class="order-card" @click="goToOrderDetail(order.orderId)">
							<div class="order-header" @click.stop="toggleOrderDetail(order)">
								<div class="business-info">
									<i class="material-icons">store</i>
									<span class="business-name">{{ order.businessName }}</span>
								</div>
								<div class="order-info">
									<span class="price">¥{{ order.totalPrice }}</span>
									<i class="material-icons" :class="{ 'rotated': order.isShowDetailet }">
										expand_more
									</i>
								</div>
							</div>
							
							<div v-show="order.isShowDetailet" class="order-details">
								<div class="detail-item" v-for="item in order.priceDetails" :key="item.foodName">
									<span class="item-name">{{ item.foodName }}</span>
									<span class="item-info">×{{ item.quantity }}</span>
									<span class="item-price">¥{{ (item.foodPrice * item.quantity).toFixed(2) }}</span>
								</div>
								<div class="detail-item delivery">
									<span class="item-name">配送费</span>
									<span class="item-price">¥{{ order.deliveryPrice }}</span>
								</div>
								<div class="detail-item total">
									<span class="item-name">总计</span>
									<span class="item-price total-price">¥{{ order.totalPrice }}</span>
								</div>
							</div>
						</div>
					</div>
				</section>

				<!-- 已退款订单 -->
				<section v-if="refundedOrders && refundedOrders.length > 0" class="order-section">
					<div class="section-header">
						<i class="material-icons">undo</i>
						<h3>已退款</h3>
						<span class="badge">{{ refundedOrders ? refundedOrders.length : 0 }}</span>
					</div>
					
					<div class="order-list">
						<div v-for="order in refundedOrders" :key="order.orderId" class="order-card" @click="goToOrderDetail(order.orderId)">
							<div class="order-header" @click.stop="toggleOrderDetail(order)">
								<div class="business-info">
									<i class="material-icons">store</i>
									<span class="business-name">{{ order.businessName }}</span>
								</div>
								<div class="order-info">
									<span class="price">¥{{ order.totalPrice }}</span>
									<i class="material-icons" :class="{ 'rotated': order.isShowDetailet }">
										expand_more
									</i>
								</div>
							</div>
							
							<div v-show="order.isShowDetailet" class="order-details">
								<div class="detail-item" v-for="item in order.priceDetails" :key="item.foodName">
									<span class="item-name">{{ item.foodName }}</span>
									<span class="item-info">×{{ item.quantity }}</span>
									<span class="item-price">¥{{ (item.foodPrice * item.quantity).toFixed(2) }}</span>
								</div>
								<div class="detail-item delivery">
									<span class="item-name">配送费</span>
									<span class="item-price">¥{{ order.deliveryPrice }}</span>
								</div>
								<div class="detail-item total">
									<span class="item-name">总计</span>
									<span class="item-price total-price">¥{{ order.totalPrice }}</span>
								</div>
							</div>
						</div>
					</div>
				</section>
			</div>
		</main>

		<!-- 底部导航 -->
		<AppFooter />
	</div>
</template>

<script>
import AppFooter from '../components/AppFooter.vue';

const ROLE = {
	ADMIN: 0,
	BUSINESS: 1,
	USER: 2
};

export default {
	name: 'OrderList',
	components: {
		AppFooter
	},
	data() {
		return {
			orderArr: [],
			user: null,
			loading: false
		};
	},
	computed: {
		// 未支付订单
		unpaidOrders() {
			return this.orderArr.filter(order => Number(order.orderState) === 0);
		},
		// 已支付订单
		paidOrders() {
			return this.orderArr.filter(order => Number(order.orderState) === 1);
		},
		// 已退款订单（orderState=4 且 refundStatus=2）
		refundedOrders() {
			return this.orderArr.filter(order => Number(order.orderState) === 4 && Number(order.refundStatus) === 2);
		}
	},
	created() {
		this.initPage();
	},
	mounted() {
		// 监听钱包余额更新事件
		window.addEventListener('wallet-balance-updated', this.handleWalletUpdate);
	},
	unmounted() {
		// 清理事件监听器
		window.removeEventListener('wallet-balance-updated', this.handleWalletUpdate);
	},
	methods: {
		// 初始化页面
		initPage() {
			// 获取用户信息
			this.user = this.$getSessionStorage('user');
			
			if (!this.user) {
				this.$router.push('/login');
				return;
			}
			
			console.log('订单页面 - 用户信息:', {
				userId: this.user.userId,
				userName: this.user.userName,
				role: this.user.role
			});
			
			// 加载订单数据
			this.loadOrders();
		},

		// 加载订单数据
		async loadOrders() {
			this.loading = true;
			
			try {
				const role = Number(this.user && this.user.role);
				let response;
				
				// 根据用户角色调用不同的API
				if (role === ROLE.USER || Number.isNaN(role)) {
					// 普通用户（默认）：获取自己的订单
					response = await this.$axios.post('OrdersController/listOrdersByUserId', 
						this.$qs.stringify({ userId: this.user.userId })
					);
				} else if (role === ROLE.BUSINESS) {
					// 商家：获取自己店铺的订单
					const businessId = this.user.businessId || this.user.userId;
					if (!businessId) {
						throw new Error('商家信息缺失：未找到商家ID');
					}
					response = await this.$axios.post('OrdersController/business/orders', 
						this.$qs.stringify({ businessId })
					);
				} else {
					console.warn('未知用户角色，按普通用户处理', role, this.user);
					response = await this.$axios.post('OrdersController/listOrdersByUserId', 
						this.$qs.stringify({ userId: this.user.userId })
					);
				}
				
				// 处理响应数据
				if (response.data && response.data.code === '200') {
					const orders = response.data.result || response.data.data || [];
					this.orderArr = this.formatOrders(orders);
					// 按下单时间倒序排列，最新订单在最上面
					this.orderArr.sort((a, b) => {
						const aTime = a && a.orderDate ? new Date(a.orderDate).getTime() : 0;
						const bTime = b && b.orderDate ? new Date(b.orderDate).getTime() : 0;
						if (aTime !== bTime) {
							return bTime - aTime;
						}
						const aId = Number(a && a.orderId) || 0;
						const bId = Number(b && b.orderId) || 0;
						return bId - aId;
					});
					console.log('订单加载成功:', this.orderArr.length, '个订单');
				} else {
					console.warn('订单加载失败:', response.data);
					this.orderArr = [];
				}
				
			} catch (error) {
				console.error('加载订单失败:', error);
				this.$toast?.error('加载订单失败，请重试');
				this.orderArr = [];
			} finally {
				this.loading = false;
			}
		},

		// 格式化订单数据
		formatOrders(orders) {
			return orders.map(order => ({
				...order,
				isShowDetailet: false,
				// totalPrice 统一代表实付金额：优先使用后端提供的 finalTotal，其次 totalPrice，最后回退到 orderTotal
				totalPrice: parseFloat(order.finalTotal || order.totalPrice || order.orderTotal || 0),
				deliveryPrice: parseFloat(order.deliveryPrice || 0),
				priceDetails: order.priceDetails || order.orderDetail || []
			}));
		},

		// 切换订单详情显示
		toggleOrderDetail(order) {
			order.isShowDetailet = !order.isShowDetailet;
		},

		// 取消订单
		async cancelOrder(orderId) {
			if (!confirm('确定要取消这个订单吗？')) {
				return;
			}
			
			try {
				const response = await this.$axios.post('OrdersController/user/cancelOrder',
					this.$qs.stringify({ orderId })
				);
				
				if (response.data && response.data.code === '200') {
					this.$toast?.success('订单已取消');
					this.loadOrders(); // 重新加载订单
				} else {
					this.$toast?.error(response.data?.message || '取消失败');
				}
			} catch (error) {
				console.error('取消订单失败:', error);
				this.$toast?.error('取消失败，请重试');
			}
		},

		// 去支付
		goToPayment(orderId) {
			this.$router.push({
				path: '/payment',
				query: { orderId }
			});
		},

		// 去订单详情
		goToOrderDetail(orderId) {
			this.$router.push({
				name: 'OrderDetail',
				params: { orderId }
			});
		},

		// 去商家列表
		goToBusinessList() {
			this.$router.push('/businessList');
		},

		// 返回上一页
		goBack() {
			this.$router.go(-1);
		},

		// 处理钱包余额更新事件
		handleWalletUpdate() {
			console.log('钱包余额更新，刷新订单列表');
			this.loadOrders();
		}
	}
};
</script>

<style scoped>
.order-list-page {
	min-height: 100vh;
	background-color: #f5f7fa;
	padding-bottom: 120px;
}

/* 顶部导航 */
.page-header {
	display: flex;
	align-items: center;
	gap: 16px;
	padding: 16px 20px;
	background: linear-gradient(135deg, #1976d2 0%, #42a5f5 100%);
	color: white;
	box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.back-btn {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 40px;
	height: 40px;
	border: none;
	background: rgba(255,255,255,0.1);
	border-radius: 50%;
	color: white;
	cursor: pointer;
	transition: all 0.2s;
}

.back-btn:hover {
	background: rgba(255,255,255,0.2);
}

.back-btn .material-icons {
	font-size: 24px;
}

.page-title {
	font-size: 20px;
	font-weight: 500;
	margin: 0;
}

/* 主要内容 */
.main-content {
	padding: 20px 16px;
}

/* 加载状态 */
.loading-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 60px 20px;
	text-align: center;
}

.loading-spinner {
	width: 40px;
	height: 40px;
	border: 4px solid #e3f2fd;
	border-top: 4px solid #1976d2;
	border-radius: 50%;
	animation: spin 1s linear infinite;
	margin-bottom: 16px;
}

@keyframes spin {
	0% { transform: rotate(0deg); }
	100% { transform: rotate(360deg); }
}

.loading-state p {
	color: #666;
	margin: 0;
}

/* 空状态 */
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 80px 20px;
	text-align: center;
}

.empty-state .material-icons {
	font-size: 64px;
	color: #ccc;
	margin-bottom: 16px;
}

.empty-state p {
	color: #999;
	font-size: 18px;
	margin: 0 0 24px 0;
}

/* 订单区域 */
.order-section {
	margin-bottom: 32px;
}

.section-header {
	display: flex;
	align-items: center;
	gap: 12px;
	margin-bottom: 16px;
	padding: 0 4px;
}

.section-header .material-icons {
	color: #1976d2;
	font-size: 24px;
}

.section-header h3 {
	font-size: 18px;
	font-weight: 500;
	color: #333;
	margin: 0;
	flex: 1;
}

.badge {
	background: #1976d2;
	color: white;
	border-radius: 12px;
	padding: 4px 12px;
	font-size: 12px;
	font-weight: 500;
}

/* 订单卡片 */
.order-card {
	background: white;
	border-radius: 12px;
	box-shadow: 0 2px 12px rgba(0,0,0,0.08);
	margin-bottom: 16px;
	overflow: hidden;
	transition: all 0.2s;
	cursor: pointer;
}

.order-card:hover {
	box-shadow: 0 4px 20px rgba(0,0,0,0.12);
	transform: translateY(-2px);
}

.order-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 16px 20px;
	cursor: pointer;
	transition: background-color 0.2s;
}

.order-header:hover {
	background-color: #f8f9fa;
}

.business-info {
	display: flex;
	align-items: center;
	gap: 12px;
}

.business-info .material-icons {
	color: #1976d2;
	font-size: 20px;
}

.business-name {
	font-size: 16px;
	font-weight: 500;
	color: #333;
}

.order-info {
	display: flex;
	align-items: center;
	gap: 12px;
}

.price {
	font-size: 18px;
	font-weight: 600;
	color: #f44336;
}

.order-info .material-icons {
	color: #666;
	font-size: 20px;
	transition: transform 0.3s;
}

.order-info .material-icons.rotated {
	transform: rotate(180deg);
}

/* 订单详情 */
.order-details {
	border-top: 1px solid #eee;
	padding: 16px 20px;
	background-color: #fafafa;
}

.detail-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 8px 0;
	font-size: 14px;
}

.detail-item.delivery {
	border-top: 1px solid #eee;
	margin-top: 8px;
	padding-top: 12px;
}

.detail-item.total {
	border-top: 2px solid #eee;
	margin-top: 8px;
	padding-top: 12px;
	font-weight: 600;
}

.item-name {
	color: #333;
	flex: 1;
}

.item-info {
	color: #666;
	margin: 0 16px;
}

.item-price {
	color: #666;
	font-weight: 500;
}

.total-price {
	color: #f44336;
	font-size: 16px;
}

/* 订单操作 */
.order-actions {
	display: flex;
	gap: 12px;
	padding: 16px 20px;
	border-top: 1px solid #eee;
}

.mdc-button {
	flex: 1;
	padding: 12px 20px;
	border-radius: 8px;
	font-size: 14px;
	font-weight: 500;
	text-transform: none;
	transition: all 0.2s;
}

.mdc-button--outlined {
	background: transparent;
	color: #f44336;
	border: 1px solid #f44336;
}

.mdc-button--outlined:hover {
	background: #f44336;
	color: white;
}

.mdc-button--raised {
	background: #1976d2;
	color: white;
	border: none;
}

.mdc-button--raised:hover {
	background: #1565c0;
}

.pay-btn {
	background: #f44336;
}

.pay-btn:hover {
	background: #d32f2f;
}

/* 响应式设计 */
@media (max-width: 600px) {
	.main-content {
		padding: 16px 12px;
	}
	
	.order-header {
		padding: 12px 16px;
	}
	
	.order-details {
		padding: 12px 16px;
	}
	
	.order-actions {
		padding: 12px 16px;
		flex-direction: column;
	}
	
	.mdc-button {
		padding: 10px 16px;
	}
}

</style>
